package com.wang.concurrency;

public class ThreadLocalClient {

	public static void main(String[] args) {
		
		//可以看到, 虽然在主线程里面对Account设置的初始值800L, 但是到子线程里面还是默认值null.
		//建议: 如果多个线程之间需要共享资源, 以达到线程之间通信的目的, 就使用同步机制;如果仅仅需要
		//隔离多个线程之间的共享冲突, 则可以选择使用ThreadLocal.
		
	     // 同一个Account
        Account3 account = new Account3(888L);
   
        new Thread(new Writer(account)).start();
        new Thread(new Reader(account)).start();

        // 主线程
        for (int i = 0; i < 10; ++i) {
            sleep(10);
            System.out.println(Thread.currentThread().getName() + "-balance: " + account.getBalance());
        }
	}
	
	
    private static class Writer implements Runnable {

        private Account3 account;

        public Writer(Account3 account) {
            this.account = account;
        }

        @Override
        public void run() {
        	System.out.println(account.getBalance());
            for (int i = 0; i < 10; ++i) {
                account.setBalance((long) i);
                sleep(10);
                System.out.println(Thread.currentThread().getName() + "-balance: " + account.getBalance());
            }
        }
    }

    private static class Reader implements Runnable {
    	
    	private Account3 account ;
    	
    	
    	public Reader(Account3 account) {
			this.account = account;		
		}

		@Override
    	public void run() {
    		System.out.println(account.getBalance());    		
    	}

    	
    	
    }

    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
	
	
}
